package ar.com.ironsoft.javaopenauth.oauth.impl;

import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import ar.com.ironsoft.javaopenauth.dto.OAuthToken;
import ar.com.ironsoft.javaopenauth.oauth.OAuthServiceWRAP;
import ar.com.ironsoft.javaopenauth.url.URLService;
import ar.com.ironsoft.javaopenauth.utils.HttpMethod;
import ar.com.ironsoft.javaopenauth.utils.MapUtils;
import ar.com.ironsoft.javaopenauth.utils.ServletActionType;
import ar.com.ironsoft.javaopenauth.utils.ValidatorUtils;

public class HotmailOAuthServiceWRAP extends OAuthServiceWRAP{

	private final static String urlMapping = "hotmail";
	private final static Set<ServletActionType> actions =  new HashSet<ServletActionType>(
			Arrays.asList(
					ServletActionType.LOGIN,
					ServletActionType.CALLBACK,
					ServletActionType.REFRESH
					)
			);
	
	public HotmailOAuthServiceWRAP(String clientKeysFileName) {
		super(urlMapping, actions,clientKeysFileName);
	}

	public String getLoginURL() {
		String url = getOauthProperties().getProperty(
				"hotmail.url.verification_code");
		url = url.replace("{0}", getConsumerKey()).replace("{1}",
				getCallbackURL());
				
		return url;
	}


	public void executeCallbackAction(String urlParameters) {
		Map<String,String> params = MapUtils.queryStringToMap(urlParameters);
		oauthToken.setVerificationCode(params.get("wrap_verification_code"));
		getAccessToken();
	}

	public OAuthToken getAccessToken() {
		ValidatorUtils.validateNullOrEmpty(oauthToken.getVerificationCode());
		
		Map<String,String> params = new HashMap<String,String>();
		params.put("wrap_verification_code", oauthToken.getVerificationCode());
		params.put("wrap_client_id", getConsumerKey());
		params.put("wrap_client_secret", getConsumerSecret());
		params.put("wrap_callback", getCallbackURL());
		params.put("idtype", "CID");
		
		URLService urlService = new URLService();
		Map<String,String> response = urlService.fetchUrl(getAccessTokenURL(), HttpMethod.POST, params);
		
		oauthToken.setRefreshToken(response.get("wrap_refresh_token"));
		oauthToken.setAccessToken(response.get("wrap_access_token"));
		oauthToken.setUserId(response.get("uid"));
		oauthToken.setSecretKey(response.get("skey"));
		oauthToken.setAccessTokenExpireTime(Integer.parseInt(response
				.get("wrap_access_token_expires_in")));
		
		return oauthToken;
	}

	public OAuthToken getRefreshToken() {
		ValidatorUtils.validateNullOrEmpty(oauthToken.getRefreshToken());
		
		Map<String,String> params = new HashMap<String,String>();
		params.put("wrap_refresh_token", oauthToken.getRefreshToken());
		
		URLService urlService = new URLService();
		Map<String,String> response = urlService.fetchUrl(getAccessTokenURL(), HttpMethod.POST, params);
		
		oauthToken.setAccessToken(response.get("wrap_access_token"));
		oauthToken.setAccessTokenExpireTime(Integer.parseInt(response
				.get("wrap_access_token_expires_in")));
		
		return oauthToken;
	}
	
}
